<template>
  <div class="register">
    <Header title="注册" />
    <div class="img">CY</div>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="username" name="user" label="用户名" placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]" />
        <van-field v-model="password" type="password" name="pass" label="密码" placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block color="#ffc400" type="primary" native-type="submit">
          注册
        </van-button>
      </div>
      <div style="margin: 16px;">
        <van-button round block type="primary" color="#ffc400" class="login" @click="toLogin">
          去登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import Header from '@/components/header.vue';
import { showToast } from 'vant';
import { reactive, toRefs } from 'vue';
import { useRouter } from 'vue-router';
export default {
  components: {
    Header,
  },
  setup() {
    const router = useRouter()
    const data = reactive({
      username: "",
      password: ""
    })
    const onSubmit = (value) => {
      // console.log(value);
      if (localStorage.userInfo) {
        let userInfo = JSON.parse(localStorage.getItem("userInfo"))        
        if (userInfo["user"] === value["user"]) {
          showToast('该用户已存在')
          return
        }
      } else {
        register(value)
      }
    }
    const register = (value) => {
      localStorage.setItem("userInfo", JSON.stringify(value))
      showToast('注册成功')
      router.push('/login')
    }
    const toLogin = () => {
      router.push('/login')
    }

    return {
      ...toRefs(data),
      onSubmit,
      toLogin,
      register
    }
  }
}
</script>

<style lang="less" scoped>
.register {
  .img {
    width: 200px;
    height: 200px;
    background-color: #ffc400;
    font-size: 80px;
    line-height: 200px;
    text-align: center;
    border-radius: 40px;
    margin: 20px auto;

    .login {
      margin-top: 20px;
    }
  }
}
</style>